﻿package com.kuanter.kuanterauto.activity;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;
/**
 * 卡片详情
 * @author kuanetr
 *
 */
public class MyKuanterCardDetailActivity extends WuyangBaseActivity {
	private TextView include_image_1tv_arrow_recharge_TV;
	private ImageView iv_card_image;
	private int cardInfoIndex;
	private Intent intent;
	private List<CardInfo> cardInfoList;
	private View card_number_item;
	private TextView card_number_tv_title;
	private TextView card_number_tv_data;
	private CardInfo currentCardInfo;
	private View card_deadline;
	private TextView card_deadline_title;
	private TextView card_deadline_data;
	private View guashi_item;
	private TextView guashi_title;
	private DataLoader dataLoader;
	private String userId;
	/**
	 * 挂失卡片请求响应
	 */
Handler handler = new Handler() {

		private ListView lv_cardInfoList;

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
//				String result = msg.getData().getString("result");
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
															// 字段值是否为false
							showToast("挂失成功");
							finishProgress();

						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast(StringUtil.geterrorMsg(result));
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
private View recharge_item;
public void onResume() {
    super.onResume();
    MobclickAgent.onResume(this);
}
public void onPause() {
    super.onPause();
    MobclickAgent.onPause(this);
}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.my_kuanter_card_detail);
		super.onCreate(savedInstanceState);
		
		intent = getIntent();
		cardInfoIndex = intent.getIntExtra("cardInfoIndex",000);
		cardInfoList = (List<CardInfo>)ObjectCache.get("cardInfoList");
		currentCardInfo = cardInfoList.get(cardInfoIndex);
		
		this.setHeaderControlViewText();
		this.initBodyControlView();
		this.setBodyControlViewText();
		this.registerListener();
		
		loadAndSetBitmap(MainConstants.HOST+currentCardInfo.getCardPicPath(),iv_card_image);
	}

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub
		super.setHeaderTitleText(headerTitle, "我的卡片");
		super.setHeaderLeftText(headerLeft, "返回");
		super.setHeaderRightText(headerRight, null);
	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		//卡号title
		card_number_item = this.findViewById(R.id.include_2_tv_card_number);
		card_number_tv_title = (TextView)card_number_item.findViewById(R.id.include_2_tv_TVtitle);
		//卡号data
		card_number_tv_data = (TextView)card_number_item.findViewById(R.id.include_2_tv_TVdata);
		
		View include_image_1tv_arrow_recharge = this
				.findViewById(R.id.include_image_1tv_arrow_recharge);
		include_image_1tv_arrow_recharge_TV = (TextView) include_image_1tv_arrow_recharge
				.findViewById(R.id.include_image_1tv_arrow_TV);
		// card_image
		iv_card_image = (ImageView) this.findViewById(R.id.iv_card_image);
		//卡片到期时间title
		card_deadline = this.findViewById(R.id.include_2_tv_card_deadline);
		card_deadline_title = (TextView)card_deadline.findViewById(R.id.include_2_tv_TVtitle);
		//卡片到期时间data
		card_deadline_data = (TextView)card_deadline.findViewById(R.id.include_2_tv_TVdata);
		//挂失
		guashi_item = this.findViewById(R.id.include_image_1tv_arrow_guashi);
		guashi_title = (TextView)guashi_item.findViewById(R.id.include_image_1tv_arrow_TV);
		//充值
		recharge_item = this.findViewById(R.id.include_image_1tv_arrow_recharge);
		
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		include_image_1tv_arrow_recharge_TV.setText("充值");
		card_number_tv_title.setText("卡号：");
		card_number_tv_data.setText(currentCardInfo.getCardNumber());
		card_deadline_title.setText("卡片到期");
		//card_deadline_data.setText(currentCardInfo.getAccountInfo().getExpireTime());//到期时间
		//挂失
		guashi_title.setText("挂失");
		
	}

	@Override
	protected void registerListener() {
		super.headerLeft.setOnClickListener(this);
		guashi_item.setOnClickListener(this);
		//充值
		recharge_item.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.header_left:
			this.finish();
			break;
		case R.id.include_image_1tv_arrow_recharge:
			Intent intent = new Intent(MyKuanterCardDetailActivity.this, RechargeActivity.class);
			intent.putExtra("card_number", currentCardInfo.getCardNumber());
			intent.putExtra("comeFromWhichActivity","MyKuanterCardDetailActivity");
			startActivity(intent);
			break;
		case R.id.include_image_1tv_arrow_guashi:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);  
			builder.setTitle("Are you sure you want to 挂失?")  
			      .setPositiveButton("Yes", new DialogInterface.OnClickListener() {  
			           List<NameValuePair> params;
					

					public void onClick(DialogInterface dialog, int id) {  
			                dataLoader = new DataLoader(MyKuanterCardDetailActivity.this);
			                List<NameValuePair> params = new ArrayList<NameValuePair>();
			                params.add(new BasicNameValuePair("cardInfo.cardNumber", currentCardInfo.getCardNumber()));
			                SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
			        		userId = sp.getString("id", "000") ;
			                params.add(new BasicNameValuePair("cardInfo.userId", userId));
			                dataLoader.DisplayData(MainConstants.HOST+HttpConfigAPI.LOST_CARD, params, handler, "", false);
			                showProgress("正在加载数据...");
			           }  
			     })  
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {  
		          public void onClick(DialogInterface dialog, int id) {  
			                dialog.cancel();  
			           }  
			       });  
			builder.create().show();

			break;
		default:
			break;
		}
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub

	}

	public void getCardImageFromNet() {

	}

	private class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
		private ImageView iv_card_image;

		public BitmapWorkerTask(ImageView iv_card_image) {
			BitmapWorkerTask.this.iv_card_image = iv_card_image;
		}

		// Decode image in background.
		@Override
		protected Bitmap doInBackground(String... params) {
			InputStream is = null;
			try {
				is = getStreamFromURL(params[0]);
			} catch (Exception e) {
				Log.i("getStreamFromURL", "getStreamFromURL is error");
			}
			Bitmap card_image_bitmap = BitmapFactory.decodeStream(is);
			return card_image_bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap bitmap) {
			iv_card_image.setImageBitmap(bitmap);
		}
	}

	public InputStream getStreamFromURL(String imageURL) throws Exception {
		InputStream is = null;
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(imageURL);
		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		return is;
	}
	
	public void loadAndSetBitmap(String imageUrl, ImageView imageView) {    
		BitmapWorkerTask task = new BitmapWorkerTask(imageView);     
		task.execute(imageUrl);
	}
}
